package com.ontoweb.workflow.filter;

import com.ontoweb.workflow.utils.RequestHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Filer:把Request中用户名灌入filter中
 */
public class UfloFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = new RequestEncodingWrapper((HttpServletRequest) request);
        crossDomain(response);
        // options请求直接放行
        if ("OPTIONS".equals(req.getMethod())) {
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_OK);
        } else {
            RequestHolder.setThreadLocal(req);
            try{
                chain.doFilter(req,response);
            } finally {
                RequestHolder.remove();
            }
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 跨域设置
     * @param servletResponse
     */
    private void crossDomain(ServletResponse servletResponse) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept," +
                        " Connection, User-Agent, Cookie, username");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
    }

}
